package com.imooc.demo.controller;

import com.imooc.demo.dataobject.ProductCategory;
import com.imooc.demo.dataobject.ProductInfo;
import com.imooc.demo.service.CategoryService;
import com.imooc.demo.service.ProductService;
import com.imooc.demo.utils.ResultVoUtil;
import com.imooc.demo.vo.ProductInfoVo;
import com.imooc.demo.vo.ProductVo;
import com.imooc.demo.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: 杨通通
 * @Date: 2021/11/4 22:59
 * @Description:
 */

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping(path = "/list")
    public ResultVo<ProductVo> list(){


        List<ProductInfo> productInfoList = productService.findUpAll();
        List<Integer> categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType())
                .collect(Collectors.toList());

        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);

        List<ProductVo> productVos = new ArrayList<>();

        for(ProductCategory productCategory:productCategoryList){
            ProductVo productVo = new ProductVo();
            productVo.setCategoryType(productCategory.getCategoryType());
            productVo.setCategoryName(productCategory.getCategoryName());

            List<ProductInfoVo> ProductInfoVos = new ArrayList<>();
            for(ProductInfo productInfo:productInfoList){
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productInfo,productInfoVo);
                    ProductInfoVos.add(productInfoVo);
                }
            }
            productVo.setProductInfoVoList(ProductInfoVos);
            productVos.add(productVo);
        }


        return ResultVoUtil.success(productVos);
    }
}